package org.codefinger.dao.impl.sql.ast;

import org.codefinger.dao.impl.SQLVisitor;
import org.codefinger.dao.impl.sql.Expression;

public class IfCaseExpression implements Expression {

	private Expression[]	exps;

	public IfCaseExpression(Expression[] exps) {
		super();
		this.exps = exps;
	}

	@Override
	public boolean matchVisit(SQLVisitor visitor) {
		int sqlSize = visitor.getSqlSize();
		int paramSize = visitor.getParamSize();
		visitor.appendSQL("CASE");
		int length = exps.length - 1;
		for (int i = 0; i < length;) {
			visitor.appendSQL(" WHEN ");
			if (exps[i++].matchVisit(visitor)) {
				visitor.appendSQL(" THEN ");
				if (exps[i++].matchVisit(visitor)) {
					continue;
				}
			}
			visitor.back(sqlSize, paramSize);
			return false;
		}
		visitor.appendSQL(" ELSE ");
		if(exps[length].matchVisit(visitor)){
			visitor.appendSQL(" END");
			return true;
		}
		visitor.back(sqlSize, paramSize);
		return false;
	}

	@Override
	public void visit(SQLVisitor visitor) {
		visitor.appendSQL("CASE");
		int length = exps.length - 1;
		for (int i = 0; i < length;) {
			visitor.appendSQL(" WHEN ");
			exps[i++].visit(visitor);
			visitor.appendSQL(" THEN ");
			exps[i++].visit(visitor);
		}
		visitor.appendSQL(" ELSE ");
		exps[length].visit(visitor);
		visitor.appendSQL(" END");
	}
	
}
